<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>摄像头测试</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            padding: 20px;
            max-width: 600px;
            margin: 0 auto;
        }
        .test-section {
            margin: 20px 0;
            padding: 15px;
            border: 1px solid #ddd;
            border-radius: 8px;
        }
        video {
            width: 100%;
            max-width: 400px;
            height: 300px;
            background: #000;
            border-radius: 8px;
        }
        button {
            padding: 10px 20px;
            margin: 5px;
            border: none;
            border-radius: 5px;
            background: #007bff;
            color: white;
            cursor: pointer;
        }
        button:disabled {
            background: #ccc;
            cursor: not-allowed;
        }
        .error {
            color: red;
            margin: 10px 0;
        }
        .success {
            color: green;
            margin: 10px 0;
        }
        .info {
            background: #f8f9fa;
            padding: 10px;
            border-radius: 5px;
            margin: 10px 0;
        }
    </style>
</head>
<body>
    <h1>摄像头功能测试</h1>
    
    <div class="test-section">
        <h2>1. 基础摄像头测试</h2>
        <button onclick="testBasicCamera()">测试摄像头访问</button>
        <div id="basic-result"></div>
        <video id="basic-video" style="display: none;"></video>
    </div>

    <div class="test-section">
        <h2>2. 设备信息</h2>
        <button onclick="getDeviceInfo()">获取设备信息</button>
        <div id="device-info"></div>
    </div>

    <div class="test-section">
        <h2>3. QR Scanner测试</h2>
        <button onclick="testQRScanner()">测试QR扫描器</button>
        <div id="qr-result"></div>
        <video id="qr-video" style="display: none;"></video>
    </div>

    <script src="https://unpkg.com/qr-scanner@1.4.2/qr-scanner.umd.min.js"></script>
    <script>
        // 基础摄像头测试
        async function testBasicCamera() {
            const resultDiv = document.getElementById('basic-result');
            const video = document.getElementById('basic-video');
            
            try {
                resultDiv.innerHTML = '<div class="info">正在请求摄像头权限...</div>';
                
                const stream = await navigator.mediaDevices.getUserMedia({ 
                    video: { 
                        facingMode: 'environment' // 后置摄像头
                    } 
                });
                
                video.srcObject = stream;
                video.style.display = 'block';
                await video.play();
                
                resultDiv.innerHTML = '<div class="success">✅ 摄像头访问成功！</div>';
                
                // 5秒后停止
                setTimeout(() => {
                    stream.getTracks().forEach(track => track.stop());
                    video.style.display = 'none';
                    resultDiv.innerHTML += '<div class="info">摄像头已停止</div>';
                }, 5000);
                
            } catch (error) {
                console.error('摄像头测试失败:', error);
                resultDiv.innerHTML = `<div class="error">❌ 摄像头测试失败: ${error.message}</div>`;
            }
        }

        // 获取设备信息
        async function getDeviceInfo() {
            const resultDiv = document.getElementById('device-info');

            try {
                let html = '<div class="info">';
                html += `<strong>用户代理:</strong> ${navigator.userAgent}<br>`;
                html += `<strong>当前协议:</strong> ${location.protocol}<br>`;
                html += `<strong>主机名:</strong> ${location.hostname}<br>`;
                html += `<strong>是否安全上下文:</strong> ${window.isSecureContext}<br>`;

                // 检查API支持
                html += `<strong>navigator.mediaDevices:</strong> ${!!navigator.mediaDevices}<br>`;
                html += `<strong>getUserMedia:</strong> ${!!navigator.mediaDevices?.getUserMedia}<br>`;
                html += `<strong>enumerateDevices:</strong> ${!!navigator.mediaDevices?.enumerateDevices}<br>`;

                // 检查是否为安全环境
                const isSecure = location.protocol === 'https:' || location.hostname === 'localhost' || location.hostname === '127.0.0.1';
                html += `<strong>摄像头可用环境:</strong> ${isSecure ? '✅ 是' : '❌ 否 (需要HTTPS)'}<br>`;

                if (navigator.mediaDevices && navigator.mediaDevices.enumerateDevices) {
                    const devices = await navigator.mediaDevices.enumerateDevices();
                    const videoDevices = devices.filter(device => device.kind === 'videoinput');
                    html += `<strong>视频设备数量:</strong> ${videoDevices.length}<br>`;

                    if (videoDevices.length > 0) {
                        html += '<strong>视频设备列表:</strong><br>';
                        videoDevices.forEach((device, index) => {
                            html += `${index + 1}. ${device.label || '未知设备'} (${device.deviceId.substring(0, 8)}...)<br>`;
                        });
                    }
                } else {
                    html += `<strong>视频设备数量:</strong> 无法检测 (API不支持)<br>`;
                }

                html += '</div>';
                resultDiv.innerHTML = html;

            } catch (error) {
                console.error('获取设备信息失败:', error);
                resultDiv.innerHTML = `<div class="error">❌ 获取设备信息失败: ${error.message}</div>`;
            }
        }

        // QR Scanner测试
        async function testQRScanner() {
            const resultDiv = document.getElementById('qr-result');
            const video = document.getElementById('qr-video');
            
            try {
                resultDiv.innerHTML = '<div class="info">正在初始化QR扫描器...</div>';
                
                // 检查是否有摄像头
                const hasCamera = await QrScanner.hasCamera();
                if (!hasCamera) {
                    throw new Error('未检测到摄像头');
                }
                
                resultDiv.innerHTML += '<div class="success">✅ 检测到摄像头</div>';
                
                // 创建扫描器
                const qrScanner = new QrScanner(
                    video,
                    result => {
                        resultDiv.innerHTML += `<div class="success">✅ 扫描成功: ${result.data}</div>`;
                        qrScanner.stop();
                        video.style.display = 'none';
                    },
                    {
                        onDecodeError: error => {
                            console.debug('QR解码错误:', error);
                        },
                        highlightScanRegion: true,
                        highlightCodeOutline: true,
                        preferredCamera: 'environment'
                    }
                );
                
                video.style.display = 'block';
                await qrScanner.start();
                
                resultDiv.innerHTML += '<div class="success">✅ QR扫描器启动成功！请扫描二维码</div>';
                
                // 30秒后自动停止
                setTimeout(() => {
                    qrScanner.stop();
                    video.style.display = 'none';
                    resultDiv.innerHTML += '<div class="info">扫描器已停止</div>';
                }, 30000);
                
            } catch (error) {
                console.error('QR扫描器测试失败:', error);
                resultDiv.innerHTML += `<div class="error">❌ QR扫描器测试失败: ${error.message}</div>`;
            }
        }

        // 页面加载时自动获取设备信息
        window.addEventListener('load', () => {
            getDeviceInfo();
        });
    </script>
</body>
</html>
